<template>
  <div class="search">
    <div class="searchInfo"></div>
    <a-button type="primary" @click="toAdd">
      <template #icon><plus-outlined /> </template>
    </a-button>
  </div>
  <a-table
    :dataSource="tableData.data"
    :columns="tableData.listColumns"
    :pagination="false"
    bordered
  >
    <template #bodyCell="{ column, index, record }">
      <template v-if="column.dataIndex === 'index'">
        {{ index + 1 }}
      </template>
      <template v-if="column.dataIndex === 'operation'">
        <a @click="toUpdate(record)">编辑</a>
      </template>
    </template>
  </a-table>

  <a-modal
    v-model:visible="addForm.visible"
    title="新增"
    okText="确定"
    cancelText="取消"
    width="30%"
    :maskClosable="false"
    centered
    @ok="add"
    @cancel="cancelAdd"
  >
    <a-form
      :model="addForm.data"
      name="addForm"
      ref="addFormRef"
      v-bind="formLayout"
    >
      <a-form-item
        label="最小内存(M)"
        name="minMem"
        :rules="[{ required: true, message: '请选择最小内存' }]"
      >
        <a-input-number placeholder="256" v-model:value="addForm.data.minMem" />
      </a-form-item>
      <a-form-item
        label="最大内存(M)"
        name="maxMem"
        :rules="[{ required: true, message: '请选择最大内存' }]"
      >
        <a-input-number placeholder="512" v-model:value="addForm.data.maxMem" />
      </a-form-item>
      <a-form-item label="java参数" name="javaArgs">
        <a-textarea placeholder="-Dspring.profiles.active=dev -Dspring.cloud.nacos.config.enabled=true -Dspring.cloud.nacos.config.server-addr=****:8848 -Dspring.cloud.nacos.config.namespace=*****" v-model:value="addForm.data.javaArgs" :rows="8" style="width: 480px;"/>
      </a-form-item>
      <a-form-item
        label="实例数"
        name="replicasNum"
        :rules="[{ required: true, message: '请选择实例数' }]"
      >
        <a-input-number placeholder="1" v-model:value="addForm.data.replicasNum"/>
      </a-form-item>
      <a-form-item
        label="硬盘大小(G)"
        name="diskSize"
        :rules="[{ required: true, message: '请选择硬盘大小' }]"
      >
        <a-input-number placeholder="1" v-model:value="addForm.data.diskSize" />
      </a-form-item>
      <a-form-item
        label="环境"
        name="envId"
        :rules="[{ required: true, message: '请选择环境' }]"
      >
        <a-select
          v-model:value="addForm.data.envId"
          :options="state.noUseEnvIdData"
          :filter-option="false"
          :fieldNames="state.envIdFieldNames"
          @change="addEnvChange"
        ></a-select>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal
    v-model:visible="updateForm.visible"
    title="修改"
    okText="确定"
    cancelText="取消"
    width="30%"
    :maskClosable="false"
    centered
    @ok="update"
    @cancel="cancelUpdate"
  >
    <a-form
      :model="updateForm.data"
      name="updateForm"
      ref="updateFormRef"
      v-bind="formLayout"
    >
      <a-form-item
        label="最小内存"
        name="minMem"
        :rules="[{ required: true, message: '请输入最小内存' }]"
      >
        <a-input-number v-model:value="updateForm.data.minMem" />
      </a-form-item>
      <a-form-item
        label="最大内存"
        name="maxMem"
        :rules="[{ required: true, message: '请输入最大内存' }]"
      >
        <a-input-number v-model:value="updateForm.data.maxMem" />
      </a-form-item>
      <a-form-item label="java参数" name="javaArgs">
        <a-textarea v-model:value="updateForm.data.javaArgs" :rows="8" style="width: 480px;"/>
      </a-form-item>
      <a-form-item
        label="实例数"
        name="replicasNum"
        :rules="[{ required: true, message: '请输入实例数' }]"
      >
        <a-input-number v-model:value="updateForm.data.replicasNum" />
      </a-form-item>
      <a-form-item
        label="硬盘大小"
        name="diskSize"
        :rules="[{ required: true, message: '请输入硬盘大小' }]"
      >
        <a-input-number v-model:value="updateForm.data.diskSize" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { reactive, ref } from "@vue/reactivity";
import {
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import { defalutResourceApi, envApi } from "@/api/devcloudApi";
import { message } from "ant-design-vue";
import { clearObject, clone, deleteKeyIgnore } from "@/util/utils";

export default defineComponent({
  name: "defalutResource",
  components: {
    ReloadOutlined,
    SearchOutlined,
    PlusOutlined,
  },
  setup() {
    const returnObj: any = {}

    const formLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    }

    // ------------ 查询条件 ------------------------
    const query = reactive({
      minMem: "",
      maxMem: "",
      replicasNum: "",
      diskSize: "",
      envId: "",
      env: "",
    });

    const search = () => {
      list();
    }

    const initQuery = () => {
      query.minMem = "";
      query.maxMem = "";
      query.replicasNum = "";
      query.diskSize = "";
      query.envId = "";
      query.env = "";
    }

    const reload = () => {
      initQuery();
      list();
    }

    returnObj.query = query;
    returnObj.search = search;
    returnObj.reload = reload;

    // ------------ 添加弹框 ------------------------
    const addFormRef = ref();
    const addForm:any = reactive({
      visible: false,
      data: {
        env: "",
      },
    });

    const initAddForm = () => {
      addForm.data.envId = state.noUseEnvIdData[0].id
    }

    const toAdd = async () => {
      if(state.noUseEnvIdData.length === 0){
        message.info("所有环境已添加");
        return
      }
      initAddForm();
      addForm.visible = true;
    }

    const cancelAdd = () => {
      addFormRef.value.resetFields();
      addForm.visible = false;
    }

    const add = () => {
      addFormRef.value.validateFields().then(async () => {
        const res = await defalutResourceApi.insert(addForm.data);
        if (res.success) {
          message.success("添加成功");
          reflush();
          cancelAdd();
        }
      });
    }

    const addEnvChange = (env: any, val: any) => {
      addForm.data.env = val.env;
    }

    returnObj.addFormRef = addFormRef;
    returnObj.addForm = addForm;
    returnObj.toAdd = toAdd;
    returnObj.cancelAdd = cancelAdd;
    returnObj.add = add;
    returnObj.addEnvChange = addEnvChange;

    // ------------ 修改弹框 ------------------------
    const updateFormRef = ref();
    const updateForm = reactive({
      visible: false,
      data: {
        env: "",
      },
    });

    const initUpdateForm = (item: any) => {
      const obj = clone(item);
      deleteKeyIgnore(
        obj,
        "id",
        "minMem",
        "maxMem",
        "javaArgs",
        "replicasNum",
        "diskSize",
        "updateVersion"
      );
      updateForm.data = obj;
    }

    const toUpdate = (item: any) => {
      initUpdateForm(item);
      updateForm.visible = true;
    }

    const cancelUpdate = () => {
      updateForm.visible = false;
      updateFormRef.value.resetFields();
    }

    const update = () => {
      updateFormRef.value.validateFields().then(async () => {
        const res = await defalutResourceApi.update(updateForm.data);
        if (res.success) {
          message.success("更新成功");
          reflush();
          cancelUpdate();
        }
      });
    }

    const updateEnvChange = (env: any, val: any) => {
      updateForm.data.env = val.env;
    }

    returnObj.updateFormRef = updateFormRef;
    returnObj.updateForm = updateForm;
    returnObj.toUpdate = toUpdate;
    returnObj.cancelUpdate = cancelUpdate;
    returnObj.update = update;
    returnObj.updateEnvChange = updateEnvChange;

    // ------------ 表格 ------------------------
    const tableData = reactive({
      data: [],
      listColumns: [
        {
          title: "序号",
          dataIndex: "index",
          align: "center",
          width: "50px",
        },
        {
          title: "最小内存",
          dataIndex: "minMem",
          key: "minMem",
          width: "100px",
          align: "center",
        },
        {
          title: "最大内存",
          dataIndex: "maxMem",
          key: "maxMem",
          width: "100px",
          align: "center",
        },
        {
          title: "java参数",
          dataIndex: "javaArgs",
          key: "javaArgs",
          width: "100px",
          align: "center",
        },
        {
          title: "实例数",
          dataIndex: "replicasNum",
          key: "replicasNum",
          width: "100px",
          align: "center",
        },
        {
          title: "硬盘大小",
          dataIndex: "diskSize",
          key: "diskSize",
          width: "100px",
          align: "center",
        },
        {
          title: "环境",
          dataIndex: "envId",
          key: "envId",
          width: "100px",
          align: "center",
          customRender: (item:any)=>{return envIdDesc(item.text)}
        },
        {
          title: "操作",
          dataIndex: "operation",
          width: "100px",
          align: "center",
        },
      ],
    });

    const envIdDesc = (id:string):string => {
      for(var i=0; i<state.envIdData.length; i++){
        const envData:any = state.envIdData[i]
        if(envData.id == id){
          return envData.env
        }
      }
      return '';
    }

    const list = async () => {
      clearObject(query);
      const res = await defalutResourceApi.list(query);
      if (res.success) {
        tableData.data = res.result;
        state.noUseEnvIdData = state.envIdData.filter((e:any)=>{
          for(let i=0; i< res.result.length; i++){
            if(res.result[i].envId === e.id){
              return false
            }
          }
          return true
        })
      }
    }

    const reflush = async () => {
      initQuery();
      await list();
    }

    const del = async (item: any) => {
      const res = await defalutResourceApi.delete(item.id);
      if (res.success) {
        message.success("删除成功");
        reflush();
      }
    }

    returnObj.tableData = tableData;
    returnObj.del = del;

    const state:any = reactive({
      envIdData: [],
      envIdFieldNames: {
        value: "id",
        label: "env",
      },
      noUseEnvIdData:[],
    });

    // ------------查询------------------

    const envIdList = async () => {
      const param = {}
      const res = await envApi.list(param);
      if (res.success) {
        state.envIdData = res.result;
      }
    }

    // --------------初始化--------------------------

    const initData = async () => {
      await envIdList()
      await reflush()
    }

    initData()

    return {
      ...returnObj,
      formLayout,
      state,
    }
  },
});
</script>

<style lang="less" scoped>
.search {
  display: flex;
  justify-content: space-between;
  padding: 40px 90px 0 50px;
}
.ant-table-wrapper {
  margin: 40px;
}

.searchInfo {
  width: 80%;
  display: flex;

  .ant-input {
    width: 180px;
    margin: 0 10px;
  }
  .ant-select {
    width: 180px;
    margin: 0 10px;
  }
  .search-btn {
    margin: 0 10px;
  }
}
.ant-pagination {
  padding-top: 20px;
}
.ant-modal {
  .ant-input {
    width: 280px;
  }
  .ant-select {
    width: 280px;
  }
  .ant-picker {
    width: 200px;
  }
  .ant-input-number {
    width: 100px;
  }
}
</style>